<?php

namespace App\Models;


class Goods extends BaseModel
{
    protected $fillable = [
        'name',
        'images_url',
        'price',
        'stock',
        'sell',
        'sort',
        'goods_number',
        'status',
	    'store_id'
    ];
    // 封面图片获取器
    public function getImagesUrlAttribute($value)
    {
        return $value;
    }

    public function setImagesUrlAttribute($value)
    {
        $this->attributes['images_url'] = env('ALIOSS_HOST').'/'.$value;
    }

    //单价修改器
    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = $value * 100;
    }

    // 单价访问器
    public function getPriceAttribute($value)
    {
        return $value = $value/100;
    }

    // 商品分类关联
    public function classify()
    {
        return $this->belongsToMany('App\Models\GoodsClassify', 'goods_to_classify');
    }
    
    // 关联商品类目
    public function getClassify()
    {
        return $this->belongsToMany(Classify::class, 'goods_bind_classifies', 'goods_id', 'classify_id');
    }

    // 关联
    public function setMeals()
    {
        return $this->belongsToMany('App\Models\SetMeal', 'set_meals_to_goods');
    }

    public function storage()
    {
        return $this->hasOne('App\Models\Storage');
    }

    public function goodsSku()
    {
        return $this->hasMany(GoodsSku::class);
    }

    public function goodstomaterial()
    {
        return $this->hasMany(GoodsToMaterial::class, 'goods_id');
    }

    public function goodsToMaterials()
    {
        return $this->belongsToMany(Material::class, 'goods_to_materials');
    }
    
    public function printarea()
    {
    	return $this->belongsToMany(PrintArea::class, 'print_area_to_goods');
    }

	// 斩断材料联系
	public function cutMaterials()
	{
		return $this->belongsToMany(Material::class, 'goods_to_materials')->withPivot('number');
	}
	
	// 返回材料库存
	static public function returnStock($cutMaterials, $stock)
	{
		if(count($cutMaterials) <= 0){
			return 0;
		}
		// 需要返回的库存
		$returns = [];
		foreach ($cutMaterials as $k => $v) {
			$returns[$v['pivot']['material_id']] = $v['pivot']['number'] * $stock;
		}
		foreach ($returns as $k => $v) {
			static $purchase = [];
			$purchase[] = PurchaseToMaterial::where('material_id', $k)
				->orderByDesc('created_at')
				->where('status', 1)
				->selectRaw('id,material_id,stock,prepare_stock')
				->first()->toArray();
		}
		if(count($purchase) <=0){
			return 0;
		}
		foreach ($purchase as $k => $v) {
			static  $multipleData = [];
			$v['stock'] += $returns[$v['material_id']];
			$v['prepare_stock'] -= $returns[$v['material_id']];
			$multipleData[] = $v;
		}
		
		$res = updateBatch('purchase_to_materials', $multipleData);
	}
}
